import json
import sys
import urllib.parse
from os import path
from urllib import request

args = len(sys.argv)
assert args == 2

music_name = sys.argv[1]
assert music_name.strip().isspace() is False
music_url_api = "https://xiaoapi.cn/API/yy_sq.php?msg={}&type=json&n=1".format(urllib.parse.quote(music_name))

with request.urlopen(music_url_api) as f:
	data = f.read()

res_dict: dict[str, str] = json.loads(str(data, "utf-8"))
print(res_dict)
resource_url: str = res_dict["url"]
singer: str = res_dict["singer"].replace(" ", "")
parse_result = urllib.parse.urlparse(resource_url)
ext_name = path.splitext(parse_result.path)[1]

request.urlretrieve(resource_url, music_name + "_" + singer + ext_name)
